using B.S.Medical.Api.Read.Application.Command.Patient;
using B.S.Medical.Api.Read.DTOS;
using B.S.Medical.Domain.Medical;
using B.S.Medical.ErrorCode;
using B.S.Medical.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.Medical.Api.Read.Application.Handler.Patient
{
    /// <summary>
    /// 根据ID获取患者信息处理器
    /// </summary>
    public class GetPatientByIdHandler : IRequestHandler<GetPatientByIdCommand, ApiResult<PatientDTO>>
    {
        private readonly IBaseRepository<PatientModel> _patientRepository;
        private readonly ILogger<GetPatientByIdHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="patientRepository">患者仓储</param>
        /// <param name="logger">日志</param>
        public GetPatientByIdHandler(
            IBaseRepository<PatientModel> patientRepository,
            ILogger<GetPatientByIdHandler> logger)
        {
            _patientRepository = patientRepository;
            _logger = logger;
        }

        /// <summary>
        /// 处理根据ID获取患者信息请求
        /// </summary>
        /// <param name="request">请求参数</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>患者信息</returns>
        public async Task<ApiResult<PatientDTO>> Handle(GetPatientByIdCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<PatientDTO>();

            try
            {
                // 根据ID查询患者
                var patient = await _patientRepository.GetValue(request.PatientId);
                
                if (patient == null || patient.IsDeleted)
                {
                    result.Code = ApiEnum.Fail;
                    result.Msg = "未找到指定ID的患者信息";
                    return result;
                }

                // 转换为DTO
                var patientDto = new PatientDTO
                {
                    Id = patient.Id,
                    Name = patient.Name,
                    IdCard = patient.IdCard,
                    Relation = patient.Relation
                };

                result.Code = ApiEnum.Success;
                result.Msg = "获取患者信息成功";
                result.Data = patientDto;

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取患者信息时发生错误，患者ID: {request.PatientId}");
                result.Code = ApiEnum.Error;
                result.Msg = "获取患者信息失败：" + ex.Message;
                return result;
            }
        }
    }
} 